<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use app\common\model\CourseModel;
use app\common\model\UserTimesModel;
use app\common\traits\SelectPage;
use app\common\model\UserModel;
use app\common\model\MessageModel;
use think\Exception;

/**
 * Class SchoolMessage
 */
class Message extends BasicAdmin
{
    use SelectPage;

    /**
     * 通知管理
     */
    protected $model = 'MessageModel';

    public function index(){
        $this->title = '通知管理';
        return  $this->_query($this->model)
            ->with(['user'])
            ->like('name')
            ->page();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 发送订阅消息
        if($this->request->isPost())
        {
            $post = $this->request->post();
            $school_id = $post['school_id'];
            $grade_id = $post['grade_id'];
            $class_id = $post['class_id'];

            $title = $this->request->post('title');
            $desc = $this->request->post('desc');

            $uids = $this->request->post('read_uid');
            if(!empty($uids))//选了用户，使用已选择的用户
            {
                $uids = explode(',', $uids);
                foreach ($uids as $uid)
                {
                    $this->sendMsg($title, $desc, $uid);
                }

            } else {
                $course_id = $this->request->post('course_id');
                if(!empty($course_id)) {
                    // 有课程先筛选课程
                    $course = CourseModel::where('id', $course_id)->find();
                    if($course['type'] == '1') {
                        // 常规课：找对应的学校、年级、班级即可
                        $users = UserModel::where(function($q) use($course){
                            $school_id = $course['school_id'];
                            $grade_id = $course['grade_id'];
                            $class_id = $course['class_id'];
                            if(!empty($school_id)){
                                $q->where('school_id', $school_id);
                            }
                            if(!empty($grade_id)){
                                $q->where('grade_id', $grade_id);
                            }
                            if(!empty($class_id)){
                                $q->where('class_id', $class_id);
                            }
                        })->all();

                        foreach ($users as $user){
                            $this->sendMsg($title, $desc, $user['id']);
                        }

                    } else {
                        // 兴趣课，找报名学生，再筛选学校、年级、班级
                        $user_ids = UserTimesModel::where('course_id',$course_id)->select();
                        foreach ($user_ids as $key=>$value)
                        {
                            //找到这个课程学生
                            $user = UserModel::where('id',$value['user_id'])->find();
                            if(!empty($school_id) and $user['school_id'] != $school_id){
                                continue;
                            }
                            if(!empty($grade_id) and $user['grade_id'] != $grade_id){
                                continue;
                            }
                            if(!empty($class_id) and $user['class_id'] != $class_id){
                                continue;
                            }
                            $this->sendMsg($title, $desc, $value['user_id']);
                        }
                    }

                } else {
                    // 没课程直接筛选学校、年级、班级
                    $users = UserModel::where(function($q) use($post){
                        $school_id = $post['school_id'];
                        $grade_id = $post['grade_id'];
                        $class_id = $post['class_id'];
                        if(!empty($school_id)){
                            $q->where('school_id', $school_id);
                        }
                        if(!empty($grade_id)){
                            $q->where('grade_id', $grade_id);
                        }
                        if(!empty($class_id)){
                            $q->where('class_id', $class_id);
                        }
                    })->all();

                    foreach ($users as $user){
                        $this->sendMsg($title, $desc, $user['id']);
                    }

                }
            }

            return ["code"=>1,"info"=>"恭喜, 数据保存成功!","data"=>""];
        }
        $this->title = '添加';
        return $this->_form($this->model, 'form');
    }

    public function sendMsg($title, $desc, $uid)
    {
        $saveData = [
            'title' =>  $title,
            'desc' =>  $desc,
            'read_uid' =>  $uid,
        ];
        MessageModel::create($saveData);

        $user = UserModel::find($uid);
        $data = [
            "touser"=> $user['openid'],
            "template_id"=> config('wechat.miniapp.jiaoshi_tpl'),
            "page"=> "pages/user/user",
            "data"=> [
                "thing1"=> [
                    "value"=> $title
                ],
                "thing6"=> [
                    "value"=> $desc
                ],
                "date3"=> [
                    "value"=> date('Y-m-d H:i')
                ],
            ]
        ];
        try {
            $ret = \We::WeMiniTemplate(config('wechat.miniapp'))->send($data);
        }catch (\Exception $e){
            // continue;
        }
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'form');
    }

    /**
     * 删除
     */
    public function del()
    {
        $this->_delete($this->model);
    }

    /**
     * 启用/关闭
     */
    public function upstatus(){
        $this->_save($this->model, [
            'status' => $this->request->request('status'),
        ],'id', ['id' => $this->request->request('id')]);
    }


}